package cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl;

import cn.com.anypay.manager.miaoma.suantaiqrcode.SuantaiQrcodeEntity;
import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.AbstractQrCodeHandler;
import cn.com.anypay.manager.miaoma.suantaiqrcode.dto.QrCodeGatewayResponse;
import cn.com.anypay.manager.service.RedirectValidationService;
import cn.com.anypay.manager.common.response.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 网址链接类型二维码处理器 (type = 1)
 *
 * 支持简单跳转和智能跳转两种版本：
 * - v1.0: 简单URL跳转
 * - v2.0: 根据设备类型智能跳转
 */
@Slf4j
@Component
public class UrlQrCodeHandler extends AbstractQrCodeHandler {

    private static final Integer SUPPORTED_TYPE = 1;
    private static final String HANDLER_NAME = "UrlQrCodeHandler";

    @Override
    public ApiResponse<Object> handle(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String targetUrl = determineTargetUrl(content, qrcode.getVersion());
        if (targetUrl == null) {
            logHandleComplete(id, "No valid URL found in content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No valid URL found");
        }

        logHandleComplete(id, "Redirecting to: " + targetUrl);
        return createRedirectResponse(targetUrl);
    }

    /**
     * 根据版本和内容确定目标URL
     *
     * @param content JSON内容
     * @param version 版本号
     * @return 目标URL
     */
    private String determineTargetUrl(JsonNode content, String version) {
        if ("2.0".equals(version)) {
            // v2.0版本支持智能跳转
            return handleSmartRedirect(content);
        } else {
            // v1.0或其他版本使用简单跳转
            return handleSimpleRedirect(content);
        }
    }

    /**
     * 处理简单重定向 (v1.0)
     */
    private String handleSimpleRedirect(JsonNode content) {
        JsonNode urlNode = content.get("url");
        return urlNode != null ? urlNode.asText() : null;
    }

    /**
     * 处理智能重定向 (v2.0)
     *
     * 这里可以根据User-Agent等信息选择不同的URL
     * 目前简化处理，使用default_url
     */
    private String handleSmartRedirect(JsonNode content) {
        // 优先级：default_url > mobile_url > wechat_url
        JsonNode defaultUrl = content.get("default_url");
        if (defaultUrl != null && !defaultUrl.asText().trim().isEmpty()) {
            return defaultUrl.asText();
        }

        JsonNode mobileUrl = content.get("mobile_url");
        if (mobileUrl != null && !mobileUrl.asText().trim().isEmpty()) {
            return mobileUrl.asText();
        }

        JsonNode wechatUrl = content.get("wechat_url");
        if (wechatUrl != null && !wechatUrl.asText().trim().isEmpty()) {
            return wechatUrl.asText();
        }

        return null;
    }

    @Override
    public Integer getSupportedType() {
        return SUPPORTED_TYPE;
    }

    @Override
    public String getHandlerName() {
        return HANDLER_NAME;
    }

    @Override
    public ApiResponse<Object> handleForGateway(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String targetUrl = determineTargetUrl(content, qrcode.getVersion());
        if (targetUrl == null) {
            logHandleComplete(id, "No valid URL found in content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No valid URL found");
        }

        // 验证URL安全性
        RedirectValidationService.ValidationResult validationResult = redirectValidationService.validateRedirectUrl(targetUrl);
        if (!validationResult.isValid()) {
            log.warn("Unsafe redirect URL rejected: {}, reason: {}", targetUrl, validationResult.getReason());
            return createErrorResponse(HttpStatus.BAD_REQUEST, "不安全的重定向URL: " + validationResult.getReason());
        }

        // 为网关模式返回结构化数据
        logHandleComplete(id, "Preparing redirect data for gateway: " + targetUrl);
        return createGatewayRedirectResponse(
            qrcode.getQrCodeId(),
            qrcode.getQrCodeName(),
            qrcode.getQrCodeType(),
            targetUrl
        );
    }
}